package com.gsp.gspframework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public final class StreamUtil {
    private static final Logger log = LoggerFactory.getLogger(StreamUtil.class);

    public static String getString(InputStream in) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (IOException e) {
            log.error("get stream error", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 将输入流复制到输出流
     * 就是简单的读写操作
     */
    public static void copyStream(InputStream inputStream, OutputStream outputStream) {
        //还可以使用try-with-resources的形式，可以简化关闭流的操作
        try {
            int length;
            byte[] buffer = new byte[4 * 1024];
            while ((length = inputStream.read(buffer, 0, buffer.length)) != -1) {
                outputStream.write(buffer,0,length);
            }
            outputStream.flush();
        } catch (Exception e) {
            log.error("copy stream failure",e);
            throw new RuntimeException(e);
        }finally {
            try {
                inputStream.close();
                outputStream.close();
            }catch (Exception e){
                log.error("close stream failure",e);
            }
        }
    }

}
